package com.keson.blue;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.ResultReceiver;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.util.List;
import java.util.Objects;

/**
 * Class Name: WifiAdmin.java<br>
 * Function:Wifi连接管理工具类<br>
 *
 原文链接：https://blog.csdn.net/qq_29882585/article/details/77102189
 * Modifications:<br>
 *
 * @author ZYT DateTime 2014-5-14 下午2:24:14<br>
 * @version 1.0<br>
 * <br>
 */
public class WifiUtil {
    // 定义一个WifiManager对象
    private static WifiManager mWifiManager;
    // 定义一个WifiInfo对象
    private static WifiInfo mWifiInfo;
    // 扫描出的网络连接列表
    private static List<ScanResult> mWifiList;
    // 网络连接列表
    private static List<WifiConfiguration> mWifiConfigurations;
    private static ConnectivityManager cm;
    private static WifiLock mWifiLock;
    private static ConnectivityManager mConnectivityManager;

    //定义几种加密方式，一种是WEP，一种是WPA，还有没有密码的情况
		public enum WifiCipherType {
			WIFICIPHER_WEP, WIFICIPHER_WPA, WIFICIPHER_NOPASS, WIFICIPHER_INVALID
		}
    public static void init(Context context) {
        if(mWifiManager==null&&mWifiInfo==null){
            // 取得WifiManager对象
            mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            // 取得WifiInfo对象
            mWifiInfo = mWifiManager.getConnectionInfo();

            mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        }

    }

    /**
     * Function:关闭wifi<br>
     * www.javaapk.com更改
     * @author ZYT DateTime 2014-5-15 上午12:17:37<br>
     * @return<br>
     */
    public static boolean closeWifi() {

        if (mWifiManager.isWifiEnabled()) {
            return mWifiManager.setWifiEnabled(false);
        }
        return false;
    }

    /**
     * Gets the Wi-Fi enabled state.检查当前wifi状态
     *
     * @return One of {@link WifiManager#WIFI_STATE_DISABLED},
     *         {@link WifiManager#WIFI_STATE_DISABLING},
     *         {@link WifiManager#WIFI_STATE_ENABLED},
     *         {@link WifiManager#WIFI_STATE_ENABLING},
     *         {@link WifiManager#WIFI_STATE_UNKNOWN}
     *
     */
    public static int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定wifiLock
    public static void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁wifiLock
    public static void releaseWifiLock() {
        // 判断是否锁定
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个wifiLock
    public static void createWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("test");
    }

    // 得到配置好的网络
    public static List<WifiConfiguration> getConfiguration() {
        return mWifiConfigurations;
    }

    // 指定配置好的网络进行连接
    public static void connetionConfiguration(int index) {
        if (index > mWifiConfigurations.size()) {
            return;
        }
        // 连接配置好指定ID的网络
        mWifiManager.enableNetwork(mWifiConfigurations.get(index).networkId,
                true);
    }

    public static void startScan() {

        //openWifi();

        mWifiManager.startScan();
        // 得到扫描结果
        mWifiList = mWifiManager.getScanResults();
        // 得到配置好的网络连接
        mWifiConfigurations = mWifiManager.getConfiguredNetworks();

    }

    // 得到网络列表
    public static List<ScanResult> getWifiList() {
        return mWifiList;
    }

    // 查看扫描结果
    public static StringBuffer lookUpScan() {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mWifiList.size(); i++) {
            sb.append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包
            // 其中把包括：BSSID、SSID、capabilities、frequency、level
            sb.append((mWifiList.get(i)).toString()).append("\n");
        }
        return sb;
    }

    public static String getMacAddress() {
        try (BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream("/sys/class/net/wlan0/address")))) {
            return input.readLine();
        } catch (IOException ex) {
            return "";
        }
    }



    /**
     * Return the basic service set identifier (BSSID) of the current access
     * point. The BSSID may be {@code null} if there is no network currently
     * connected.
     *
     * @return the BSSID, in the form of a six-byte MAC address:
     *         {@code XX:XX:XX:XX:XX:XX}
     */
    public static String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    public static String getSSID(){
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID();
    }

    public static int getIpAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    /**
     * Each configured network has a unique small integer ID, used to identify
     * the network when performing operations on the supplicant. This method
     * returns the ID for the currently connected network.
     *
     * @return the network ID, or -1 if there is no currently connected network
     */
    public static int getNetWordId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    /**
     * Function: 得到wifiInfo的所有信息<br>
     *
     * @author ZYT DateTime 2014-5-14 上午11:03:32<br>
     * @return<br>
     */
    public static String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }


    /**
     * 获得指定SSID的保护类型
     * @return
     */
    public static String getWifiType(String strSSID){
        startScan();
        for(int i=0;i<mWifiList.size();i++){
            if(mWifiList.get(i).SSID.equals(strSSID)){
                String strType=mWifiList.get(i).capabilities;
                return strType;
            }
        }
        return "";
    }
    // 添加一个网络并连接
    public static void addNetWork(WifiConfiguration configuration) {
        int wcgId = mWifiManager.addNetwork(configuration);
        mWifiManager.enableNetwork(wcgId, true);
    }

    // 断开指定ID的网络
    public static void disConnectionWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    /**
     * Function: 打开wifi功能<br>
     *
     * @author ZYT DateTime 2014-5-14 上午11:01:11<br>
     * @return true:打开成功；false:打开失败<br>
     */
    public static boolean openWifi() {
        boolean bRet = true;
        if (!mWifiManager.isWifiEnabled()) {
            bRet = mWifiManager.setWifiEnabled(true);
        }
        return bRet;
    }

    /**
     * Function: 提供一个外部接口，传入要连接的无线网 <br>
     *
     * @author ZYT DateTime 2014-5-13 下午11:46:54<br>
     * @param SSID
     *            SSID
     * @param Password
     * @param Type
     * <br>
     *            没密码：{WifiCipherType#WIFICIPHER_NOPASS}
     *            WEP加密： { WifiCipherType#WIFICIPHER_WEP}
     *            WPA加密： { WifiCipherType#WIFICIPHER_WPA}
     * @return true:连接成功；false:连接失败<br>
     */
    public static boolean connect(String SSID, String Password, WifiCipherType Type) {
        if (!openWifi()) {
            return false;
        }
        // 开启wifi功能需要一段时间(我在手机上测试一般需要1-3秒左右)，所以要等到wifi
        // 状态变成WIFI_STATE_ENABLED的时候才能执行下面的语句
        while (mWifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING) {
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒在检测……
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }



        WifiConfiguration wifiConfig = createWifiInfo(SSID, Password, Type);
        //
        if (wifiConfig == null) {
            return false;
        }

        WifiConfiguration tempConfig = isExsits(SSID);

        int tempId = wifiConfig.networkId;
        if (tempConfig != null) {
            tempId = tempConfig.networkId;
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        int netID = mWifiManager.addNetwork(wifiConfig);

        // 断开连接
        //mWifiManager.disconnect();
        // 重新连接
        // netID = wifiConfig.networkId;
        // 设置为true,使其他的连接断开
        boolean bRet = mWifiManager.enableNetwork(netID, true);
        //mWifiManager.reconnect();
        return bRet;
    }

    // 查看以前是否也配置过这个网络
    private static WifiConfiguration isExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager
                .getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    private static WifiConfiguration createWifiInfo(String SSID, String Password,
                                                    WifiCipherType Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";
        if (Type == WifiCipherType.WIFICIPHER_NOPASS) {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WEP) {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == WifiCipherType.WIFICIPHER_WPA) {

            // config.preSharedKey = "\"" + Password + "\"";
            // config.hiddenSSID = true;
            // config.allowedAuthAlgorithms
            // .set(WifiConfiguration.AuthAlgorithm.OPEN);
            // config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            // config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            // config.allowedPairwiseCiphers
            // .set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            // config.status = WifiConfiguration.Status.ENABLED;

            // 修改之后配置
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.CCMP);

        } else {
            return null;
        }
        return config;
    }

    /**
     * Function:判断扫描结果是否连接上<br>
     *
     * @author ZYT DateTime 2014-5-14 上午11:31:40<br>
     * @param result
     * @return<br>
     */
    public static boolean isConnect(Context context, ScanResult result) {
        if (result == null) {
            return false;
        }
        //获得当前已连接网络
        cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获得网络信息
        NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        if (wifi == NetworkInfo.State.CONNECTED || wifi== NetworkInfo.State.CONNECTING) {
            mWifiInfo = mWifiManager.getConnectionInfo();
            String g2 = "\"" + result.SSID + "\"";
            if (mWifiInfo.getSSID() != null && mWifiInfo.getSSID().endsWith(g2)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断指定的SSID是否已连接成功，调用该方法前提是要连接的网络enableNetwork的返回值为true
     * @param SSID
     * @return
     */
    public static boolean isWifiConnected(Context context, String SSID){
        //获得当前已连接网络
        cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //获得网络信息的连接状态
        NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();

        //如果正在连接，则让它进入循环，并睡个100ms再检测
        while(wifi == NetworkInfo.State.CONNECTING ){
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒再检测……
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
            wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState();
        }
        //如果连接成功，则返回真
        if (wifi == NetworkInfo.State.CONNECTED ) {
            return true;
        }

        return false;
    }

    /**
     * 判断指定的SSID是否已连接成功，调用该方法前提是要连接的网络enableNetwork的返回值为true
     * @param SSID
     * @return
     */
    public static boolean isConnected(Context context, String SSID){
        //获得当前已连接的网络信息
        //如果不是指定的，就循环并重新获得，直到已连接的网络是指定的
        //获得当前已连接网络
        cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        //获得已连接的WIFI信息
        //获得网络信息的连接状态
        NetworkInfo.State wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        System.out.print(wifi.toString());
        while(wifi == NetworkInfo.State.CONNECTING ){
            try {
                // 为了避免程序一直while循环，让它睡个100毫秒再检测……
                Thread.currentThread();
                Thread.sleep(100);
            } catch (InterruptedException ie) {

            }
            wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                    .getState();
        }
        if (wifi == NetworkInfo.State.CONNECTED ) {
            return true;
        }

        return false;
    }

    /**
     * Function: 将int类型的IP转换成字符串形式的IP<br>
     *
     * @author ZYT DateTime 2014-5-14 下午12:28:16<br>
     * @param ip
     * @return<br>
     */
    public static String ipIntToString(int ip) {
        try {
            byte[] bytes = new byte[4];
            bytes[0] = (byte) (0xff & ip);
            bytes[1] = (byte) ((0xff00 & ip) >> 8);
            bytes[2] = (byte) ((0xff0000 & ip) >> 16);
            bytes[3] = (byte) ((0xff000000 & ip) >> 24);
            return Inet4Address.getByAddress(bytes).getHostAddress();
        } catch (Exception e) {
            return "";
        }
    }

    public static int getConnNetId() {
        // result.SSID;
        mWifiInfo = mWifiManager.getConnectionInfo();
        return mWifiInfo.getNetworkId();
    }

    /**
     * Function:信号强度转换为字符串<br>
     *
     * @author ZYT DateTime 2014-5-14 下午2:14:42<br>
     * @param level
     * <br>
     */
    public static String singlLevToStr(int level) {

        String resuString = "无信号";

        if (Math.abs(level) > 100) {
        } else if (Math.abs(level) > 80) {
            resuString = "弱";
        } else if (Math.abs(level) > 70) {
            resuString = "强";
        } else if (Math.abs(level) > 60) {
            resuString = "强";
        } else if (Math.abs(level) > 50) {
            resuString = "较强";
        } else {
            resuString = "极强";
        }
        return resuString;
    }

    /**
     *添加到网络
     * @param wcg
     */
    public static boolean addNetwork(WifiConfiguration wcg) {
        if (wcg == null) {
            return false;
        }
        //receiverDhcp = new ReceiverDhcp(ctx, mWifiManager, this, wlanHandler);
        //ctx.registerReceiver(receiverDhcp, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION));
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        mWifiManager.saveConfiguration();
        System.out.println(b);
        return b;
    }

    public static boolean connectSpecificAP(ScanResult scan) {
        //标志要连接的网络是否已经配置过
        boolean networkInSupplicant = false;
        //连接结果
        boolean connectResult = false;

        //得到所有网络的配置信息的集合
        List<WifiConfiguration> list = mWifiManager.getConfiguredNetworks();

        // 重新连接指定AP
        //mWifiManager.disconnect();

        //如果集合为空
        if(list==null){
            return false;
        }

        /********************执行连接命令************************/
        //遍历配置信息的集合，如果要连接的网络的配置信息已存在，则连接该网络
        for (WifiConfiguration w : list) {
            // 将指定AP 名字转化
            // String str = convertToQuotedString(info.ssid);
            //
            if (w.BSSID != null && w.BSSID.equals(scan.BSSID)) {

                connectResult = mWifiManager.enableNetwork(w.networkId, true);

                // mWifiManager.saveConfiguration();
                networkInSupplicant = true;
                break;
            }
        }

        //如果没有配置过，设置和添加配置并连接
        if (!networkInSupplicant) {
            //配置网络信息，密码为空
            WifiConfiguration config = CreateWifiInfo(scan, "");

            //添加配置好的网络并连接
            connectResult = addNetwork(config);
        }
        /**************以上只是根据配置执行连接指令，并不代表能够连接成功************/

        return connectResult;
    }

    // 然后是一个实际应用方法，只验证过没有密码的情况：
    public static WifiConfiguration CreateWifiInfo(ScanResult scan, String Password) {

        WifiConfiguration config = new WifiConfiguration();
        config.hiddenSSID = false;
        config.status = WifiConfiguration.Status.ENABLED;

        if (scan.capabilities.contains("WEP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers
                    .set(WifiConfiguration.GroupCipher.WEP104);

            config.SSID = "\"" + scan.SSID + "\"";

            config.wepTxKeyIndex = 0;
            config.wepKeys[0] = Password;
            // config.preSharedKey = "\"" + SHARED_KEY + "\"";
        } else if (scan.capabilities.contains("PSK")) {
            //
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else if (scan.capabilities.contains("EAP")) {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
            config.allowedAuthAlgorithms
                    .set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedPairwiseCiphers
                    .set(WifiConfiguration.PairwiseCipher.TKIP);
            config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.SSID = "\"" + scan.SSID + "\"";
            config.preSharedKey = "\"" + Password + "\"";
        } else {
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

            config.SSID = "\"" + scan.SSID + "\"";
            // config.BSSID = info.mac;
            config.preSharedKey = null;
            //
        }

        return config;
    }

//    判断热点状态：https://blog.csdn.net/weixin_43835637/article/details/91350820
    public static boolean isWifiApEnabled() {
        try {
            Method method = Objects.requireNonNull(mWifiManager).getClass().getMethod("isWifiApEnabled");
            method.setAccessible(true);
            return (Boolean) method.invoke(mWifiManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
//    开关热点
    public static boolean openWifiAp() {
        try {
            Field mField = Objects.requireNonNull(mConnectivityManager).getClass().getDeclaredField("TETHERING_WIFI");
            mField.setAccessible(true);
            int mTETHERING_WIFI = (int)mField.get(mConnectivityManager);
            Field iConnMgrField = mConnectivityManager.getClass().getDeclaredField("mService");
            iConnMgrField.setAccessible(true);
            Object iConnMgr = iConnMgrField.get(mConnectivityManager);
            Class<?> iConnMgrClass = Class.forName(iConnMgr.getClass().getName());
            Method mStartTethering1 = iConnMgrClass.getMethod("startTethering", int.class, ResultReceiver.class,boolean.class);
            mStartTethering1.setAccessible(true);
            mStartTethering1.invoke(iConnMgr, mTETHERING_WIFI, null, true);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

//    public static boolean closeWifiAp() {
//        try {
//            Field mField = Objects.requireNonNull(mConnectivityManager).getClass().getDeclaredField("TETHERING_WIFI");
//            mField.setAccessible(true);
//            int mTETHERING_WIFI = (int)mField.get(mConnectivityManager);
//            Field iConnMgrField = mConnectivityManager.getClass().getDeclaredField("mService");
//            iConnMgrField.setAccessible(true);
//            Object iConnMgr = iConnMgrField.get(mConnectivityManager);
//            Class<?> iConnMgrClass = Class.forName(iConnMgr.getClass().getName());
//            Method mStartTethering1 = iConnMgrClass.getMethod("startTethering", int.class, ResultReceiver.class,boolean.class);
//            mStartTethering1.setAccessible(true);
//            mStartTethering1.invoke(iConnMgr, mTETHERING_WIFI, null, false);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return false;
//        }
//        return true;
//    }




//原文链接：https://blog.csdn.net/wyjlovecr7/article/details/76243200
    private static final String DEFAULT_AP_PASSWORD = "12345678";
    public static int WIFI_AP_STATE_DISABLED = 11;
    public enum WifiSecurityType {
        WIFICIPHER_NOPASS, WIFICIPHER_WPA, WIFICIPHER_WEP, WIFICIPHER_INVALID, WIFICIPHER_WPA2
    }

    public static void openWifiAp(String ssid, String password, WifiSecurityType Type) {
        //配置热点信息。
        WifiConfiguration wcfg = new WifiConfiguration();
        wcfg.SSID = new String(ssid);
        wcfg.networkId = 1;
        wcfg.allowedAuthAlgorithms.clear();
        wcfg.allowedGroupCiphers.clear();
        wcfg.allowedKeyManagement.clear();
        wcfg.allowedPairwiseCiphers.clear();
        wcfg.allowedProtocols.clear();
        if(Type == WifiSecurityType.WIFICIPHER_NOPASS) {
            wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN, true);
            wcfg.wepKeys[0] = "";
            wcfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            wcfg.wepTxKeyIndex = 0;
        } else if(Type == WifiSecurityType.WIFICIPHER_WPA) {
            //密码至少8位，否则使用默认密码
            if(null != password && password.length() >= 8){
                wcfg.preSharedKey = password;
            } else {
                wcfg.preSharedKey = DEFAULT_AP_PASSWORD;
            }
            wcfg.hiddenSSID = false;
            wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wcfg.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            //wcfg.allowedKeyManagement.set(4);
            wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        } else if(Type == WifiSecurityType.WIFICIPHER_WPA2) {
            //密码至少8位，否则使用默认密码
            if(null != password && password.length() >= 8){
                wcfg.preSharedKey = password;
            } else {
                wcfg.preSharedKey = DEFAULT_AP_PASSWORD;
            }
            wcfg.hiddenSSID = false;
            wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            wcfg.allowedKeyManagement.set(4);
            //wcfg.allowedKeyManagement.set(4);
            wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        }
        try {
            Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", wcfg.getClass());
            Boolean rt = (Boolean)method.invoke(mWifiManager, wcfg);
        } catch (Exception e) {

        }
        openWifiAp();
    }
    //获取热点状态
    public static int getWifiAPState() {
        int state = -1;
        try {
            Method method2 = mWifiManager.getClass().getMethod("getWifiApState");
            state = (Integer) method2.invoke(mWifiManager);
        } catch (Exception e) {
        }
        return state;
    }

    //关闭WiFi热点
    public static void closeWifiAp() {
        if (getWifiAPState() != WIFI_AP_STATE_DISABLED) {
            try {
                Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
                method.setAccessible(true);
                WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager);
                Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
                method2.invoke(mWifiManager, config, false);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    //获取热点ssid
    public static String getWifiApSsid() {
        try {
            Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
            WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager);
            return configuration.SSID;
        } catch (Exception e) {
            return null;
        }
    }
    //获取热点密码
    public static String getWifiApPassword(){
        try {
            Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
            WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager);
            return configuration.preSharedKey;
        } catch (Exception e) {
            return null;
        }

    }
    //获取热点安全类型
    public static int getWifiApSecurity(){
        WifiConfiguration configuration;
        try {
            Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
            configuration = (WifiConfiguration)method.invoke(mWifiManager);
        } catch (Exception e) {
            return WifiSecurityType.WIFICIPHER_INVALID.ordinal();
        }

//        if(DEBUG)Log.i(TAG,"getSecurity security="+configuration.allowedKeyManagement);
        if(configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)) {
            return WifiSecurityType.WIFICIPHER_NOPASS.ordinal();
        }else if(configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
            return WifiSecurityType.WIFICIPHER_WPA.ordinal();
        }else if(configuration.allowedKeyManagement.get(4)) { //4 means WPA2_PSK
            return WifiSecurityType.WIFICIPHER_WPA2.ordinal();
        }
        return WifiSecurityType.WIFICIPHER_INVALID.ordinal();
    }
}